package com.kwin.test.config;

import java.lang.reflect.Field;

import org.apache.ibatis.reflection.MetaObject;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import lombok.extern.slf4j.Slf4j;

/**
 * 通用参数统一处理
 */
@Slf4j
public class CustomMetaObjectHandler implements MetaObjectHandler {
    

    public static final String NAME = "name";

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("{}", metaObject.getOriginalObject());
        if(validField(metaObject, NAME)) {
            Object value = getFieldValByName(NAME, metaObject);
            Class<?> clzz = metaObject.getGetterType(NAME);
            if(String.class.isAssignableFrom(clzz)) {
                setFieldValByName(NAME, "test", metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        
        if(validField(metaObject, NAME)) {
            Object value = getFieldValByName(NAME, metaObject);
            Class<?> clzz = metaObject.getGetterType(NAME);
            if(String.class.isAssignableFrom(clzz)) {
                setFieldValByName(NAME, "test", metaObject);
            }
        }
    }

    private boolean validField(MetaObject metaObject, String fieldName) {
        Object obj = metaObject.getOriginalObject();
        if(obj == null) {
            return false;
        }
        Field[] fields = obj.getClass().getDeclaredFields();
        if(fields.length == 0) {
            return false;
        }

        for(Field field : fields) {
            if(field.getName().equals(fieldName)) {
                return true;
            }
        }
        return false;


    }
}
